AlgoWiki

Binary search

Binary search is an algorithm technique based on the Divide and conquer paradigm. The most common example of binary search is to find an element in a sorted array in logarithmic time.

Description

Suppose you have an array AA of nn objects, and a predicate function PP, such that for each element aAa\in A, P(a)P(a) returns either true\mathrm{true} or false\mathrm{false}. Thus PP tests some property of the elements in AA

Furthermore, the array must satisfy the binary search property: there exists an index ii such that P(aj)P(a_j) is true\mathrm{true} for all jij\geq i, and P(aj)P(a_j) is false\mathrm{false} for all j<ij < i. When this holds, binary search can be used to find this index ii, i.e. the index of the leftmost element aa such that P(a)P(a) is true. The following pseudocode shows how.

int lo = 0,
    hi = (int)A.size() - 1,
    res = -1;
while (lo <= hi) {
    int mid = (lo+hi)/2;
    if (P(A[mid])) {
        res = mid;
        hi = mid - 1;
    } else {
        lo = mid + 1;
    }
}

At completion, res\mathrm{res} will be the index of the leftmost element aa such that P(a)P(a) is true (the index that we called ii above), or 1-1 if no element in the array satisfies the property. Since the value of hilo\mathrm{hi} - \mathrm{lo} decreases by roughly half on every iteration, the algorithm takes time O(log(n))O(\log(n)), where nn is the size of the input array AA

Applications

Say we want to find a specific element xx in a sorted array, or report that is not in the array. To do that, we define the property

P(a):={trueif axfalseotherwiseP(a) := \left\{\begin{array}{ll} \mathrm{true} & \textrm{if } a \geq x \\ \mathrm{false} & \textrm{otherwise} \end{array}\right.

Since the array is sorted, we can see that the binary search property is fulfilled: there is an index ii such that for all jij \geq i, ajxa_j \geq x is true, and for all j<ij < i, ajxa_j \geq x is false. Thus, using binary search we can find the index of the first element that satisfies the property in logarithmic time. If this element is equal to xx, then we're done, otherwise (and in the case that res=1\mathrm{res} = -1) we can report that xx is not in the array.

It is also very common to use binary search when finding the minimum or maximum solution, even if there is no explicit array involved. Consider the problem The Monkey and the Oiled Bamboo. Notice that strength satisfies the binary search property: if we have a bigger strength factor than the minimum necessary, we will be able to reach the top, but if we have a smaller strength factor, then we won't be able to reach the top. Thus we can binary search kk, doing O(log(n))O(\log(n)) simulations of jumping to the top to evaluate the predicate PP for different values of kk

Variants

Binary search can also be applied over real numbers instead of integers. In that case the technique is known as the Bisection method

Problems

See also